package com.tanhua.common.service.impl;

import com.aliyun.oss.OSS;
import com.tanhua.common.config.AliyunOSSConfig;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class PicUploadServiceImpl implements PicUploadService {
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};
    @Autowired
    private OSS ossClient;

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    @Override
    public PicUploadResult upload(MultipartFile uploadFile) {
        PicUploadResult picUploadResult = new PicUploadResult();

        //我们这里只能上传图片，所以规定后缀名笔记满足条件
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {
            picUploadResult.setStatus("error");
            return picUploadResult;
        }

        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        try {
            ossClient.putObject(aliyunOSSConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            picUploadResult.setStatus("error");//上传失败
            return picUploadResult;
        }

        picUploadResult.setStatus("done");
        //filePath是文件的名称；但是想要访问的话还需要一个前缀，前缀需要到oss的bucket的文件管理中查看
        //这里的前缀已经写到aliyun.properties中的aliyun.oss.urlPrefix=https://tanhua-yzp.oss-cn-chengdu.aliyuncs.com/
        picUploadResult.setName(this.aliyunOSSConfig.getUrlPrefix() + filePath);
        picUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return picUploadResult;
    }

    private String getFilePath(String sourceFileName) {
        return new SimpleDateFormat("yyyy/MM/dd/").format(new Date())//解析当前时间
                + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999)//加上随机数
                + "." + StringUtils.substringAfterLast("abc.jpg", ".");//加上图片后缀名
    }
}
